﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml.Serialization;
using ScratchNet.Common;
namespace ScratchNet
{
    public class FileUtil
    {
        public static Dictionary<HardBoardType, IOBoardContent> ReadIOVarConfig()
        {
            string filePath = "C:\\RaytoolSoftware\\2DCutAhead2.0\\DeflutMachineConfigParamters\\IOVar.xml";
            if (File.Exists(filePath))
            {
                HashSet<HardBoardType> hardBoardTypes = new HashSet<HardBoardType>() 
                {
                    HardBoardType.EDS2000,HardBoardType.EDS2010
                };
                var hDMonitors = ReadXMLFile<List<HDMonitor>>(filePath)
                    .Where(p => hardBoardTypes.Contains(p.HDType)).ToList();
                return hDMonitors
                    .GroupBy(hdm => hdm.HDType)  // 按照HDType分组
                    .Select(hdGroup => new IOBoardContent
                    {
                        HDType = hdGroup.Key,
                        nSlaveNum = hdGroup.FirstOrDefault().listHDChildren.FirstOrDefault().nSlaveNum,
                        bEds300ModuleName = hdGroup.FirstOrDefault().bEds300ModuleName,
                        IOTypeCountDict = hdGroup
                            .SelectMany(hdm => hdm.listHDChildren)  // 将所有子项展开为单一序列
                            .GroupBy(mpv => mpv.IOType)             // 按照IOType分组
                            .ToDictionary(
                                group => group.Key,                 // 分组键（IOType）
                                group => group.ToList()
                            )
                    })
                    .ToDictionary(p => p.HDType);

            }
            else
            {
                throw new Exception("Invalid XML");
            }
        }
        public static T ReadXMLFile<T>(string filePath) where T : new()
        {
            if (File.Exists(filePath) == false)
            {
                return new T();
            }
            try
            {
                T xmlContent;
                XmlSerializer xs = new XmlSerializer(typeof(T));
                Encoding encoding = new UTF8Encoding(false);
                using (FileStream fs = new FileStream(filePath, FileMode.Open))
                {
                    using (StreamReader sr = new StreamReader(fs, encoding))
                    {
                        xmlContent = (T)xs.Deserialize(sr.BaseStream);
                    }
                }
                return xmlContent;
            }
            catch (Exception ex)
            {
                return new T();
            }
        }
    }
}
